import requests,re,time,json
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from random import randint
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 Edg/87.0.664.75',
}
login_url = 'https://id.sspu.edu.cn/cas/login'
submit_url = 'https://hsm.sspu.edu.cn/selfreport/DayReport.aspx'
flag= ""
def send_email(mail,mail_pwd,status,username):
    try:
        if(status=='fail'):
            content = MIMEText(username+"每日一报失败了", 'plain', 'utf-8')
            content['Subject'] = "别睡啦起来日报!"
        else:
            content = MIMEText(t+" "+username+" 每日一报已成功", 'plain', 'utf-8')
            content['Subject'] = "现在已经是"+t2+"快快去睡觉吧!"
        content['To'] = mail
        content['From'] = mail     
        smtp_server = SMTP_SSL('smtp.qq.com', 465)
        smtp_server.login(mail, mail_pwd)
        smtp_server.sendmail(mail, mail, content.as_string())
    except:pass

def job(username,password,mail,mail_pwd,info):
    f_time = 32
    while(f_time>0):
        try:
            sessions = requests.session()
            res = sessions.get(login_url, headers=headers)
            lt = "".join(re.findall(r'<input type="hidden" name="lt" value="(.*)"/>', res.text))
            data = {
                "username": username,
                "password": password,
                "_eventId": "submit",
                "errors": "0",
                "lt": lt
                }
            sessions.post(login_url,data=data,headers=headers) 
            data = {'__EVENTTARGET': 'p1$ctl00$btnSubmit','F_STATE':info,"p1$TiWen":"35.2","p1$BaoSRQ":t,"p1$CheckAddress":"p1_CheckAddress"}     
            sessions.get(submit_url,data=data,headers=headers)
            time.sleep(3)
            res = sessions.post(submit_url,data=data,headers=headers)
            sessions.close()         
            if(len(re.findall(r"提交成功",res.text))):
                if(mail and mail_pwd):send_email(mail,mail_pwd,'success',username)
                break
            else:
                if(mail and mail_pwd):send_email(mail,mail_pwd,'fail',res.text)
                raise Exception
        except: 
            time.sleep(f_time)
            f_time<<1

def start_job():
    print(t+'日报任务开始')
    with open('./data.json','r',encoding='utf-8')as f:
        data_list = json.load(f)
        for data in data_list:
            username,password,mail,mail_pwd,info=data['username'],data['password'],data.get('mail',''),data.get('mail_pwd',''),data['info']
            job(username,password,mail,mail_pwd,info)
    print(t+'日报任务完成') 
while True:
    ran_t = randint(300,600)
    t,t2=time.strftime("%Y-%m-%d",time.localtime()),time.strftime("%H:%M",time.localtime())
    if(flag!=t and f"00:40"<=t2<=f"09:40"):
        start_job()
        flag,ran_t = t,17*60*60
    else:time.sleep(1800+ran_t) 
    
